//
//  KABMineTicketVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/16.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMineTicketVC.h"
#import "KABMineTicketTCell.h"
#import "KABTicketDetailVC.h"
#import <MJRefresh.h>
#import "XDAFNetworking.h"
#import "GlobalHeader.h"
#import "ApiManager.h"
#import "KABModel.h"
#import "MBProgressHUD+XDPrompt.h"
#import "SGScanningQRCodeVC.h"
#import "SGAlertView.h"
#import <AVFoundation/AVFoundation.h>
#import "KABTicketScanVC.h"
#import <UIScrollView+EmptyDataSet.h>

@interface KABMineTicketVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;

@property (strong, nonatomic) KABExhibitionOrder *ticketList;

@end

static NSString *const kReuseCellId = @"KABMineTicketTCell";
static NSInteger const kRequestTicketSize = 20;

@implementation KABMineTicketVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"我的门票";
    
    // 管理员才有扫一扫功能
    if ([KABModel sharedInstance].userInfo.is_gm) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"exhibition_scan"] style:UIBarButtonItemStylePlain target:self action:@selector(scanBarBtnTapped:)];
    }
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 45.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    self.tableView.mj_footer = self.mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"空空如也" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.ticketList.exhibition_order_list.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABMineTicketTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.section < self.ticketList.exhibition_order_list.count) {
        [cell configViewWithExhOrderDetail:self.ticketList.exhibition_order_list[indexPath.section]];
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5.9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    KABTicketDetailVC *vc = [[KABTicketDetailVC alloc] init];
    vc.ticketDetail = self.ticketList.exhibition_order_list[indexPath.section];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - event response
- (void)scanBarBtnTapped:(UIBarButtonItem *)item {
    // 1、 获取摄像设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (status == AVAuthorizationStatusNotDetermined) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        KABTicketScanVC *scanningQRCodeVC = [[KABTicketScanVC alloc] init];
                        [self.navigationController pushViewController:scanningQRCodeVC animated:YES];
                        NSLog(@"主线程 - - %@", [NSThread currentThread]);
                    });
                    NSLog(@"当前线程 - - %@", [NSThread currentThread]);
                    
                    // 用户第一次同意了访问相机权限
                    NSLog(@"用户第一次同意了访问相机权限");
                    
                } else {
                    
                    // 用户第一次拒绝了访问相机权限
                    NSLog(@"用户第一次拒绝了访问相机权限");
                }
            }];
        } else if (status == AVAuthorizationStatusAuthorized) { // 用户允许当前应用访问相机
            KABTicketScanVC *scanningQRCodeVC = [[KABTicketScanVC alloc] init];
            [self.navigationController pushViewController:scanningQRCodeVC animated:YES];
        } else if (status == AVAuthorizationStatusDenied) { // 用户拒绝当前应用访问相机
            SGAlertView *alertView = [SGAlertView alertViewWithTitle:@"⚠️ 警告" delegate:nil contentTitle:@"请去-> [设置 - 隐私 - 相机 - Kabu] 打开访问开关" alertViewBottomViewType:(SGAlertViewBottomViewTypeOne)];
            [alertView show];
        } else if (status == AVAuthorizationStatusRestricted) {
            NSLog(@"因为系统原因, 无法访问相册");
        }
    } else {
        SGAlertView *alertView = [SGAlertView alertViewWithTitle:@"⚠️ 警告" delegate:nil contentTitle:@"未检测到您的摄像头, 请在真机上测试" alertViewBottomViewType:(SGAlertViewBottomViewTypeOne)];
        [alertView show];
    }
}

#pragma mark - private methods
- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.ticketList.totalLoad) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestTicketListWithHeader:isHeader];
}

- (KABExhibitionOrder *)ticketListWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.ticketList;
    }
    
    KABExhibitionOrder *temp = [KABExhibitionOrder yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    if (!temp) {
        return self.ticketList;
    }
    
    if (AddMore && self.ticketList) {
        [self.ticketList addMoreWithData:temp];
    } else {
        self.ticketList = temp;
    }
    return self.ticketList;
}

#pragma mark - network request
- (void)requestTicketListWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    NSInteger startIndex = isHeader ? 0 : self.ticketList.exhibition_order_list.count;
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"index" : @(startIndex),
                           @"size" : @(kRequestTicketSize)};
    NSLog(@"我的门票的参数：%@", pars);
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiExhibitionOrderList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"我的门票返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self ticketListWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"我的门票失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

@end
